import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators } from "@angular/forms";
import { IonicPage, Nav, NavParams, MenuController } from 'ionic-angular';
import { Storage, IonicStorageModule } from '@ionic/storage';
import { URLSearchParams } from '@angular/http';

import { HomePage } from '../home/home';
import { HelperService } from "../../providers/services.helper";
import { ApiService } from "../../providers/services.api";
import { GlobalData } from "../../providers/GlobalData";

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  authForm: FormGroup;
  logins: { shop_icon: string, login_save: boolean, is_sandbox: boolean } = { shop_icon: '', login_save: true, is_sandbox: false };

  constructor(private menu: MenuController,
    public fb: FormBuilder,
    private storage: Storage,
    public navCtrl: Nav,
    public navParams: NavParams,
    public helperService: HelperService,
    public api: ApiService,
    public global: GlobalData) {
    this.authForm = fb.group({
      'username': [null, Validators.compose([Validators.required, Validators.minLength(1)])],
      'password': [null, Validators.compose([Validators.required, Validators.minLength(5)])]
    });
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit LoginPage');
    this.storage.get('settings').then((setting) => {
      this.storage.get('activate').then((activate) => {
        this.storage.get('user').then((user) => {
          this.logins.shop_icon = activate.shop_icon;
          this.logins.login_save = setting.login_save;
          this.logins.is_sandbox = setting.sandbox_mode;
          if (setting.login_save) {
            this.authForm.patchValue({
              username: user.login,
            });
          } else {
            this.authForm.patchValue({
              username: '',
            });
          }
          if (!setting.sandbox_mode) {
            this.global.curEnvir = 'PRODUCTION_MODE';
            setting.sandbox_mode = false;
          } else {
            this.global.curEnvir = 'SANDBOX_MODE';
            setting.sandbox_mode = true;
          }
        });
      });
    });
  }

  submitForm(value: any): void {
    this.helperService.showLoading();
    console.log('Login Form submited!')
    this.storage.get('settings').then((setting) => {
      this.storage.get('activate').then((activate) => {
        console.log('Invalid Token, get token:')
        let urlSearchParams = new URLSearchParams();
        urlSearchParams.append('locale', setting.locale);
        urlSearchParams.append('app_id', activate.passcode);
        let body = urlSearchParams.toString();
        this.api.auth(body).then(auth => {
          console.log('auth success:' + auth);

          // store token
          setting.token = auth['token'];

          let urlParams = new URLSearchParams();
          urlParams.append('token', auth['token']);
          urlParams.append('locale', setting.locale);
          urlParams.append('login', value.username);
          urlParams.append('password', value.password);
          urlParams.append('device_type', '');
          urlParams.append('device_token', '');
          let body = urlParams.toString();

          this.api.login(body).then(data => {
            console.log('login success:' + data['user_id']);
            this.storage.get('user').then((user) => {
              let warehouse_id;
              if (setting.warehouse_lock) {
                let urlParams2 = new URLSearchParams();
                urlParams2.append('token', auth['token']);
                urlParams2.append('locale', setting.locale);
                urlParams2.append('warehouse_id', setting.warehouse_id);
                this.api.settings(urlParams2.toString()).then(lock => {
                  console.log('set warehouse lock success:' + lock);
                }, (err) => {
                  console.log('set warehouse lock error:' + err);
                });
                warehouse_id = setting.warehouse_id;
              } else {
                warehouse_id = data['warehouse_id'];
              }

              user.id = data['user_id'];
              user.name = data['name'];
              user.shop_id = data['shop_id'];
              user.level = data['user_level'];
              user.login = urlParams.get('login');
              user.password = urlParams.get('password');
              user.isLogin = true;
              user.invoice_prefix = data['invoice_prefix'];
              user.warehouse = {
                warehouse_id: warehouse_id,
                warehouse_tel: data['tel'],
                warehouse_EN_US: data['warehouse_EN_US'],
                warehouse_ZH_HK: data['warehouse_ZH_HK'],
                warehouse_ZH_CN: data['warehouse_ZH_CN']
              };

              this.global.curUser = user;

              setting.warehouse_id = warehouse_id;
              setting.warehouse = data['warehouse'];
              setting.departments = data['departments'];
              setting.epsonPrinters = {};

              var departmentPrinters: { [department_id: number]: any; } = {};
              for (let department of data['departments']) {
                for (let product of setting.epsonPrinters) {
                  if (department == product.department_id) {
                    if (!departmentPrinters[department]) {
                      departmentPrinters[department] = [];
                      departmentPrinters[department].push({
                        ipAddr: '192.168.1.237',
                        port: 8008,
                        deviceId: 'local_printer',
                        deviceObj: null,
                        printerObj: null,
                        builder: null,
                        connected: false,
                        printing: false
                      });
                    } else {
                      departmentPrinters[department].push({
                        ipAddr: '192.168.1.239',
                        port: 8008,
                        deviceId: 'local_239',
                        deviceObj: null,
                        printerObj: null,
                        builder: null,
                        connected: false,
                        printing: false
                      });
                    }
                  }
                }
              }

              setting.epsonPrinters = departmentPrinters;

              this.global.warehouse = user.warehouse;
              this.global.curEpsonPrinters = departmentPrinters;
              this.global.departments = data['departments'];
              this.storage.set('user', user);
              this.storage.set('settings', setting);

              this.helperService.hideLoading();
              this.navCtrl.setRoot(HomePage);
            });
          }, (error) => {
            console.log('login error:' + error);
            this.helperService.hideLoading();
            this.helperService.showToast(error);
          });
        }, (error) => {
          console.log('auth error:' + error);
          this.helperService.hideLoading();
          this.helperService.showToast(error);
        });
      });
    });
  }

  changeCheckbox(isSave) {
    this.logins.login_save = isSave;
    this.storage.get('settings').then((setting) => {
      setting.login_save = isSave;
      this.storage.set('settings', setting);
    });
  }

  changeEnvir(isSandbox) {
    this.logins.is_sandbox = isSandbox;
    this.storage.get('settings').then(setting => {
      if (!this.logins.is_sandbox) {
        this.global.curEnvir = 'PRODUCTION_MODE';
        setting.sandbox_mode = false;
      } else {
        this.global.curEnvir = 'SANDBOX_MODE';
        setting.sandbox_mode = true;
      }
      this.storage.set('settings', setting);
    });
  }

  ionViewDidEnter() {
    this.menu.swipeEnable(false, 'left-menu');
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

}
